// 通知函数
function showNotification(message, isError = false) {
    const notification = document.getElementById('notification');
    const messageEl = document.getElementById('notification-message');

    // 重置状态
    notification.classList.remove('show', 'hide');
    void notification.offsetWidth; // 触发重绘

    // 设置内容和样式
    notification.className = isError ? 'notification error' : 'notification';
    messageEl.textContent = message;

    // 显示通知
    notification.classList.add('show');

    // 自动消失逻辑
    const hideNotification = () => {
        notification.classList.remove('show');
        notification.classList.add('hide');
        setTimeout(() => {
            notification.classList.remove('hide');
        }, 500);
    };

    // 3秒后自动消失
    let timeoutId = setTimeout(hideNotification, 3000);

    // 点击关闭按钮
    const closeBtn = document.getElementById('notification-close');
    const handleClose = () => {
        clearTimeout(timeoutId);
        hideNotification();
        closeBtn.removeEventListener('click', handleClose);
    };

    closeBtn.addEventListener('click', handleClose);
}


document.addEventListener('DOMContentLoaded', function() {
    // 粒子背景效果
    particlesJS('particles-js', {
        particles: {
            number: { value: 80, density: { enable: true, value_area: 800 } },
            color: { value: "#ff6b6b" },
            shape: { type: "circle" },
            opacity: { value: 0.5, random: true },
            size: { value: 3, random: true },
            line_linked: { enable: true, distance: 150, color: "#4ecdc4", opacity: 0.4, width: 1 },
            move: { enable: true, speed: 2, direction: "none", random: true, straight: false, out_mode: "out" }
        },
        interactivity: {
            detect_on: "canvas",
            events: {
                onhover: { enable: true, mode: "repulse" },
                onclick: { enable: true, mode: "push" }
            }
        }
    });

    // 初始化数据
    // 计算从5月31日开始到现在的天数
    const startDate = new Date('2025-05-31'); // 开始日期
    const today = new Date(); // 当前日期
    // 计算天数差（包括开始当天）
    const currentDay = Math.floor((today - startDate) / (1000 * 60 * 60 * 24)) + 1;
    const totalDays = 100;
    // 确保天数在1-100范围内
    const clampedDay = Math.min(Math.max(currentDay, 1), totalDays);
    const motivationQuotes = [
        "每一次汗水都是脂肪的眼泪！坚持下去！",
        "今天的努力，明天的骄傲！你已经比昨天更强了！",
        "罗马不是一天建成的，好身材也不是一天练成的！",
        "不要羡慕别人的身材，你正在创造自己的奇迹！",
        "运动不是惩罚，而是对自己身体的奖励！",
        "你今天的坚持，就是明天镜子里的惊喜！",
        "脂肪在燃烧，意志在成长！你是最棒的！",
        "每一次想放弃的时候，想想当初为什么开始！",
        "自律给你自由！坚持下去，你会感谢现在的自己！",
        "你正在创造历史——自己身体的历史！"
    ];

    // 从服务器获取记录
    let records = [];

    // API基础URL
    const API_BASE_URL = 'http://localhost:1009';

    // DOM元素
    const progressBar = document.getElementById('progressBar');
    const currentDayEl = document.getElementById('currentDay');
    const daysCompletedEl = document.getElementById('daysCompleted');
    const daysRemainingEl = document.getElementById('daysRemaining');
    const completionPercentEl = document.getElementById('completionPercent');
    const motivationTextEl = document.getElementById('motivationText');
    const newMotivationBtn = document.getElementById('newMotivationBtn');
    const photoInput = document.getElementById('photoInput');
    const photoPreview = document.getElementById('photoPreview');
    const dayNotes = document.getElementById('dayNotes');
    const saveBtn = document.getElementById('saveBtn');
    const timeline = document.getElementById('timeline');
    const galleryGrid = document.getElementById('galleryGrid');

    // 初始化页面
    async function initPage() {
        // 从服务器获取记录
        await fetchRecords();

        // 更新进度
        updateProgress();

        // 更新标题
        updateTitle();

        // 显示随机激励语
        showRandomMotivation();

        // 加载时间线
        renderTimeline();

        // 加载图库
        renderGallery();

        // 设置事件监听器
        setupEventListeners();
    }

    // 从服务器获取记录
    async function fetchRecords() {
        try {
            const response = await fetch(`${API_BASE_URL}/api/records`);
            if (!response.ok) {
                throw new Error('获取记录失败');
            }
            records = await response.json();
        } catch (error) {
            console.error('获取记录时出错:', error);
            // 使用默认记录
            records = [

            ];
        }
    }

    // 更新进度信息
    function updateProgress() {
        const percent = Math.round((clampedDay / totalDays) * 100);

        progressBar.style.width = `${percent}%`;
        currentDayEl.textContent = clampedDay;
        daysCompletedEl.textContent = clampedDay;
        daysRemainingEl.textContent = totalDays - clampedDay;
        completionPercentEl.textContent = `${percent}%`;
    }

    // 设置事件监听器
    function setupEventListeners() {
        addRecordButton.addEventListener('click', addRecord);
        motivationButton.addEventListener('click', showRandomMotivation);
    }


    // 添加更新标题的函数
    function updateTitle() {
        const titleEl = document.querySelector('title');
        titleEl.textContent = `100日减脂计划-第${clampedDay}天`;
    }

    // 显示随机激励语
    function showRandomMotivation() {
        const randomIndex = Math.floor(Math.random() * motivationQuotes.length);
        motivationTextEl.textContent = motivationQuotes[randomIndex];
        motivationTextEl.classList.add('animate__animated', 'animate__pulse');

        // 移除动画类以便下次可以重新触发
        setTimeout(() => {
            motivationTextEl.classList.remove('animate__animated', 'animate__pulse');
        }, 1000);
    }

    // 渲染时间线
    function renderTimeline() {
        timeline.innerHTML = '';

        // 只显示最近的10条记录（可选）
        const recentRecords = records.slice(-10);

        recentRecords.forEach((record, index) => {
            const timelineItem = document.createElement('div');
            timelineItem.className = `timeline-item ${index % 2 === 0 ? 'left' : 'right'}`;

            const content = `
                <div class="timeline-content">
                    <div class="timeline-date">第${record.day}天 - ${record.date}</div>
                    <div class="timeline-text">${record.note}</div>
                    ${record.photo ? `<img src="${record.photo}" alt="第${record.day}天照片" class="timeline-photo">` : ''}
                </div>
            `;

            timelineItem.innerHTML = content;
            timeline.appendChild(timelineItem);
        });
    }

    // 渲染图库
    function renderGallery() {
        galleryGrid.innerHTML = '';
        console.log('===>renderGallery' , records)
        records.forEach(record => {
            const galleryItem = document.createElement('div');
            galleryItem.className = 'gallery-item';

            const content = `
                <img src="${API_BASE_URL}${record.photoUrl}" alt="第${record.day}天照片" class="gallery-img">
                <div class="gallery-info">
                    <div class="gallery-day">第${record.day}天</div>
                    <div class="gallery-date">${record.date}</div>
                    <div class="gallery-date" style="border-bottom: 3px solid chartreuse ">${record.note}</div>
                </div>
            `;

            galleryItem.innerHTML = content;
            galleryGrid.appendChild(galleryItem);
        });
    }

    // 上传照片到服务器
    async function uploadPhoto(file, day) {
        const formData = new FormData();
        formData.append('photo', file);
        formData.append('day', day);

        try {
            const response = await fetch(`${API_BASE_URL}/api/upload`, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error('照片上传失败');
            }

            const data = await response.json();
            return data.photoUrl;
        } catch (error) {
            console.error('上传照片时出错:', error);
            return null;
        }
    }

    // 保存记录到服务器
    async function saveRecord(record) {
        try {
            const response = await fetch(`${API_BASE_URL}/api/records`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(record)
            });

            if (!response.ok) {
                throw new Error('保存记录失败');
            }

            return await response.json();
        } catch (error) {
            console.error('保存记录时出错:', error);
            return null;
        }
    }

    // 设置事件监听器
    function setupEventListeners() {

        // 时间线展开/收起按钮
        const toggleTimelineBtn = document.getElementById('toggleTimelineBtn');
        const timelineContainer = document.getElementById('timelineContainer');
        toggleTimelineBtn.addEventListener('click', function() {
            timelineContainer.classList.toggle('collapsed');
            toggleTimelineBtn.textContent = timelineContainer.classList.contains('collapsed')
                ? '展开时间线'
                : '收起时间线';
        });

        // 新激励语按钮
        newMotivationBtn.addEventListener('click', showRandomMotivation);

        // 照片上传
        photoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    photoPreview.innerHTML = `<img src="${event.target.result}" alt="今日照片">`;
                    photoPreview.querySelector('img').style.display = 'block';

                    // 添加动画效果
                    photoPreview.querySelector('img').classList.add('animate__animated', 'animate__fadeIn');
                };
                reader.readAsDataURL(file);
            }
        });

        // 保存记录
        saveBtn.addEventListener('click', async function() {
            const note = dayNotes.value.trim();
            const file = photoInput.files[0];
            let photoUrl = null;

            // 如果有上传照片，先上传照片
            if (file) {
                photoUrl = await uploadPhoto(file, clampedDay);
                if (!photoUrl) {
                    showNotification('照片上传失败，请重试！');
                    return;
                }
            }

            // 准备记录数据
            const today = new Date();
            const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;

            const record = {
                day: clampedDay,
                date: dateStr,
                photoUrl: photoUrl,
                note: note
            };

            // 保存记录到服务器
            const result = await saveRecord(record);
            if (!result) {
                showNotification('保存记录失败，请重试！');
                return;
            }

            // 更新本地记录
            const existingIndex = records.findIndex(r => r.day === parseInt(result.record.day));
            if (existingIndex >= 0) {
                records[existingIndex] = result.record;
            } else {
                records.push(result.record);
            }

            console.log('===>records' , records)
            // 重新渲染时间线和图库
            renderTimeline();
            renderGallery();

            // 清空表单
            dayNotes.value = '';
            photoPreview.innerHTML = '';
            photoInput.value = '';

            // 显示成功消息
            showNotification('记录保存成功！');
        });

        // 添加通知关闭按钮事件
        document.getElementById('notification-close').addEventListener('click', () => {
            document.getElementById('notification').classList.remove('show');
        });
    }

    // 初始化页面
    initPage();
});
